-module(cloap_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).
-export([use_sso/0]).
-define(APP, cloap).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    Dispatch = cowboy_router:compile([
        {'_', [
               {"/", cowboy_static, {priv_file, ?APP, "index.html"}},
               {"/static/[...]", cowboy_static, {priv_dir, ?APP, "static"}},
               {"/websocket", cloap_handler, []},
               {"/cloap/app/:appid/:script/[:file]", cloap_module_handler, []}
        ]}
    ]),

    cowboy:start_http(cloap_portal_listener, 100,
        [{port, application:get_env(?APP, port, 80)}],
        [
         {env, [{dispatch, Dispatch}]},
         {middlewares, middlewares()}
        ]
    ),

    
    DispatchEsb = cowboy_router:compile(
                    [
                     {'_', 
                      [ 
                        {"/", cowboy_static, {priv_file, ?APP, "index.html"}},
                        {"/role/:dim/[:id]",  role_handler, []},
                        {"/role/:dim/:id/[:action]", role_handler, []},
                        {"/user/[:id]", user_handler, []},
                        {"/msgpack/[:msgtype]", msgpack_handler, []}
                      ]
                     }
                    ]),

    cowboy:start_http(cloap_esb_listener, 100,
        [{port, application:get_env(?APP, esb_port, 8080)}],
        [
         {env, [{dispatch, DispatchEsb}]}
        ]
    ),


    

    start_admin(),
    cloap_sup:start_link().

stop(_State) ->
    ok.


middlewares() ->
    case use_sso() of
        false ->
            [cowboy_router, cowboy_handler];
        true ->
            [cowboy_cas_client, cowboy_router, cowboy_handler]
    end.


start_admin() ->
    {ok, _} = msgpack_rpc_server:start(
                ?APP, 
                tcp, 
                newspack_api, 
                [{port, application:get_env(cloap, admin_port, 9199)}]).


use_sso() ->
    application:get_env(?APP, sso, false).
